﻿namespace ClassyBlog.Web
{
    using System;
    using System.Linq;
    using System.Web.Mvc;

    using DataAccess;
    using DomainObjects;
    using Infrastructure;

    public class PagesController : ApplicationController
    {
        public PagesController(IPageRepository repository)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            Repository = repository;
        }

        protected IPageRepository Repository { get; private set; }

        public ActionResult Index(int page, string relativePath)
        {
            var total = Repository.Count(relativePath);
            var pageSize = Blog.PagesPerPage;

            var pages = Repository.FindAll(relativePath)
                                  .OrderByDescending(p => p.PublishedAt)
                                  .Skip(Pagination.StartIndex(page, pageSize))
                                  .Take(pageSize)
                                  .ToList();

            if (!pages.Any())
            {
                return HttpNotFound();
            }

            var category = Category.Parse(relativePath);

            var model = new CategorizedPageList(
                page, total, pageSize, pages, category);

            return View(model);
        }

        public ActionResult Show(string relativePath)
        {
            var page = Repository.FindOne(relativePath);

            var result = (page == null) ||
                         (page.PublishedAt >= Clock.UtcNow()) ?
                         HttpNotFound() as ActionResult :
                         View(new ItemModel<Page>(page));

            return result;
        }
    }
}